﻿using System;
using System.Threading.Tasks;
using System.Windows.Forms;
using Framework;
using Koala.Framework;

namespace Koala.JiraTool.TaskList
{
    public partial class MainFormControl : UserControl, IDependency
    {
        #region Field

        private readonly ITaskController _taskController;
        private readonly INotificationController _notificationController;
        private readonly ILoginController _loginController;

        #endregion Field

        #region Constructor

        public MainFormControl(Lazy<TaskListControl> taskListControl, ITaskController taskController, INotificationController notificationController, ILoginController loginController)
        {
            _taskController = taskController;
            _notificationController = notificationController;
            _loginController = loginController;
            if (DesignMode)
            {
                InitializeComponent();
            }
            else
            {
                InitializeComponent(taskListControl.Value);
            }
        }

        #endregion Constructor

        #region Event

        private void btnStart_Click(object sender, EventArgs e)
        {
            StartOrStop(true);
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            StartOrStop(false);
        }

        #endregion Event

        #region Private Method

        private void StartOrStop(bool isStart)
        {
            if (!_loginController.IsLogin())
            {
                _notificationController.Message("请先登录...");
                return;
            }
            tlcList.SetControl(false);
            var m = (isStart ? "启动" : "停止");
            _notificationController.Message("正在" + m + "选中任务，请稍后。");

            var task = Task.Factory.StartNew(() =>
                {
                    var list = tlcList.GetSelectList();
                    foreach (var taskInfo in list)
                    {
                        if (isStart)
                            _taskController.StartTask(taskInfo.Id);
                        else
                            _taskController.StopTask(taskInfo.Id);
                        var taskModel = _taskController.GetTask(taskInfo.Keyword);
                        taskInfo.Status = taskModel.Status;
                    }
                    Invoke(new Action(() => tlcList.SetDataGridView(list)));
                });
            task.ContinueWith(t =>
                {
                    Invoke(new Action(() =>
                        {
                            tlcList.SetControl(true);
                            _notificationController.Message(m + "任务操作执行完毕。");
                        }));
                });
        }

        #endregion Private Method
    }
}